# encoding: utf-8
# author: 侯佳涛
# file_name: tasks
# create_time: 2022/2/15, 下午2:55
from django.core.mail import send_mail
from django.conf import settings  # 因为进程相互独立，celery进程如果要调用Django进程中的配置参数，需要在main文件中先声明

from celery_tasks.main import celery_app


# celery的失败重发机制
# bind参数设置为True，保证装饰器的参数作为优先级高的参数传入send_email_verify方法中
# retry_backoff设置错误重发次数，第n次重发时间算法：retry_backoff * 2 ^ (n - 1)s
@celery_app.task(bind=True, name='send_email_verify', retry_backoff=3)
def send_email_verify(self, to_email, verify_url):
    """发送邮件异步任务"""
    subject = "美多商城邮箱验证"
    html_message = '<p>尊敬的用户您好！</p>' \
                   '<p>感谢您使用美多商城。</p>' \
                   '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                   '<p><a href="%s">%s<a></p>' % (to_email, verify_url, verify_url)

    try:
        send_mail(subject=subject, message='', from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email], html_message=html_message)
    except Exception as e:
        raise self.retry(exc=3, max_retries=3)  # 发送失败进行重发


"""
启动celery命令: celery -A celery_tasks.main worker -l info
celery默认1个cpu开启4个进程，如果要多开，使用-c或者--concurrency参数指定，进程不能开过多，可以用协程代替
协程命令：celery -A celery_tasks.main worker -l info -P eventlet -c 1000
"""
